﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Com.Charence.PassManager.BusinessComponents;
using Com.Charence.PassManager.Common;
using Com.Charence.PassManager.UI.Web.Common;
using Microsoft.AspNet.SignalR;

namespace Com.Charence.PassManager.UI.Web.Controllers
{
    public class AuthenticateController : Controller
    {
        private string QRToken
        {
            get { return Session["Auth_QRToken"].ToString(); }
            set { Session["Auth_QRToken"] = value; }
        }

        public ActionResult Login()
        {
            QRToken = Guid.NewGuid().ToString("N").ToLower();

            var loginBC = new AuthenticateBC();
            loginBC.AddQRToken(QRToken);

            ViewBag.QRToken = QRToken;

            return View();
        }

        [HttpPost]
        public ActionResult DoLogin()
        {
            var loginBC = new AuthenticateBC();
            string message;
            var result = loginBC.DoLogin(QRToken, out message);
            if (result > 0)
            {
                AppContext.Current.LoginUserID = result;

                System.Web.Security.FormsAuthentication.SetAuthCookie(result.ToString(), false);
                return RedirectToAction("Index", "Dashboard");
            }
            return RedirectToAction("Login", "Authenticate");
        }

        [HttpPost]
        public ActionResult DoLoginOnWeb(string username, string password)
        {
            var loginBC = new AuthenticateBC();
            string errMsg;
            var result = loginBC.DoLoginOnWeb(username, password, out errMsg);

            if (!string.IsNullOrEmpty(errMsg))
            {
                return RedirectToAction("Login", "Authenticate");
            }

            AppContext.Current.LoginUserID = result;

            var commonBC = new CommonBC();
            AppContext.Current.LoginUserInfo = commonBC.GetUserBasicInfo(result);

            System.Web.Security.FormsAuthentication.SetAuthCookie(result.ToString(), false);
            return RedirectToAction("Index", "Dashboard");
        }

        public JsonResult QRScaned(string tokenString, string userName, string password)
        {
            string errMsg;

            var loginBC = new AuthenticateBC();
            var connectionId = loginBC.TryQRLogin(tokenString, userName, password, out errMsg);

            var hubContext = GlobalHost.ConnectionManager.GetHubContext<AuthenticateHub>();
            hubContext.Clients.Client(connectionId).DoLogin();

            if (!string.IsNullOrEmpty(errMsg))
            {
                return Json(new 
                {
                    LoginResult = "Failed",
                    Message = errMsg
                }, JsonRequestBehavior.AllowGet);
            }
            return null;
        }


    }
}
